import logging
from django.core.mail import send_mail
from django_redis import get_redis_connection
from ffmall.settings import EMAIL_HOST_USER
from celery_tasks.celery_main import app

logger = logging.getLogger(__name__)  # 用文件名命名
# DURATION = 3  # 有效时长，单位分钟
EMAIL_KEY = 'email:verification:%s'


@app.task(name='send_email_task')  # 通过celery提交任务
def send_email_task(email, verification_code, duration):
    """
    发送邮箱验证码
    :param email: 收件人邮箱
    :param verification_code: 验证码
    :param duration: 过期时间
    :return:
    """
    try:
        email_format = {
            'subject': 'FFmall验证码',
            'message': '',
            'html_message':  # % format f-string {}
                f"""
                        <h3>欢迎您注册FFmall，祝您购物愉快！</h3>
                        <p>您的验证码是：<span style="color:#FF5722">{verification_code}</span></p>
                        <p>注意：验证码的有效时长为：{duration}</p>
                """,
            'from_email': EMAIL_HOST_USER,  # 发送邮箱
            'recipient_list': [email],  # 接收邮箱
        }
        res_email = send_mail(**email_format)
    except Exception as e:
        logger.error('验证码有那发送[异常][email:%s, message:%s]' % (email, e))
    else:
        if res_email != 1:
            logger.warning("验证码获取[失败][email: %s]" % email)
        else:
            # 将验证码放入redis数据库
            cache = get_redis_connection(alias='verify_code')  # 获取redis连接对象
            cache.set(EMAIL_KEY % email, verification_code, duration * 60)  # 时间*60
            logger.info("验证码邮件发送[正常][email:%s verification_code:%s]" % (email, verification_code))